package com.job;

import com.common.utils.DateUtils;
import com.common.utils.PythonUtils;
import com.common.utils.SysConfig;
import com.common.utils.test.SocketTest;
import com.model.domain.data.GetDataObdGpsInfoDO;
import com.model.domain.device.GetDevice25ObdInfoDO;
import com.model.domain.device.GetDeviceObdBaseInfoDO;
import com.model.domain.device.GetDeviceObdGpsInfoDO;
import com.model.pojo.data.DataObdGpsInfo;
import com.model.pojo.device.*;
import com.model.pojo.system.SimInfo;
import com.service.data.DataObdGpsInfoService;
import com.service.device.*;
import com.service.system.SimInfoService;
import io.swagger.models.auth.In;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.DateUtil;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * TODO
 *
 * @Description
 * @Author tm
 * @Date 2023-05-25 22:22
 **/
@Slf4j
@Component
@RequiredArgsConstructor
public class DeviceObdJob {
    private final DeviceObdGpsInfoService deviceObdGpsInfoService;
    private final DeviceObdDayInfoService deviceObdDayInfoService;
    private final DeviceObdBaseInfoService deviceObdBaseInfoService;
    private final DataObdGpsInfoService dataObdGpsInfoService;
    private final SimInfoService simInfoService;
    private final  Device25ObdInfoService device25ObdInfoService;
    private final DeviceObdWorkTimeDayStatisticsInfoService deviceObdWorkTimeDayStatisticsInfoService;
    /**
     * 统计每天的GPS信息
     * @author tm
     * @date 2023-05-25 22:23
     */
    //使用
    @Scheduled(cron = "0 20 1 * * ?")
    public void countEveryDayObdGpsInfo(){
        if(SysConfig.getJobSwitch()==0)return;
        Date date = new Date();
        for(int i=1;i<2;i++){
            List<DeviceObdDayInfo> dayList = new ArrayList<>();
            String tableName = "device_obd_gps_info_";
            date = DateUtils.addDays(date,-1);
            int year = Integer.parseInt(DateUtils.getYear(date));
            int month = Integer.parseInt(DateUtils.getMonth(date));
            int day = Integer.parseInt(DateUtils.getDate(date));
            String dayStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,date);
            dayStr = dayStr.replaceAll("-", "");
            GetDeviceObdGpsInfoDO getDeviceObdGpsInfoDO = new GetDeviceObdGpsInfoDO();
            getDeviceObdGpsInfoDO.setTableName(tableName+dayStr);
            List<Map<String,Object>> list = deviceObdGpsInfoService.getListGroupBy(getDeviceObdGpsInfoDO);
            if(list!=null && list.size()>0){
                list.forEach(item ->{
                    String dtu = (String)item.get("dtu");
                    DeviceObdDayInfo dayInfo = new DeviceObdDayInfo();
                    dayInfo.setDtu(dtu);
                    dayInfo.setYear(year);
                    dayInfo.setMonth(month);
                    dayInfo.setDay(day);
                    dayInfo.setCreatedTime(new Date());
                    dayList.add(dayInfo);
                });
            }

            if(dayList!=null && dayList.size()>0){
                deviceObdDayInfoService.saveList(dayList);
            }
        }
    }


   

    /**
     * 更新OBD设备的在线状态
     * @author tm
     * @date 2023-05-27 10:10
     */
    //使用
    @Scheduled(cron = "0 */1 * * * ?")
    public void updateOBDOnLineStatus(){
        if(SysConfig.getJobSwitch()==0)return;
        String tableName = "device_pcb_gps_info_";
        String dayStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,new Date());
        dayStr = dayStr.replaceAll("-", "");
        GetDeviceObdBaseInfoDO getDeviceObdBaseInfoDO = new GetDeviceObdBaseInfoDO();
        getDeviceObdBaseInfoDO.setSortRow("createTime");
        getDeviceObdBaseInfoDO.setSortOrder("desc");
        List<DeviceObdBaseInfo> baseList = deviceObdBaseInfoService.getAllList(getDeviceObdBaseInfoDO);
        List<DeviceObdBaseInfo> updateBaseList = new ArrayList<>();
        if(baseList!=null && baseList.size()>0){
            for(DeviceObdBaseInfo baseInfo:baseList){
                if(baseInfo.getDtu().startsWith("01bw99000000")){
                    System.out.println("11111");
                }
                int onLineStatus = 1;//在线状态，0离线，1在线
                if(baseInfo.getDataTime() == null){
                    onLineStatus =0;
                }else {
                    //查询设备最新一条记录的时间距离当前时间是否大于2分钟
                    //大于2分钟则为离线，反之在线
                    String time1 = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, new Date());
                    String time2 = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, baseInfo.getDataTime());
                    List<Long> list = DateUtils.getDistanceTime(time1, time2);
                    if (list.get(0) > 0 || list.get(1) > 0 || list.get(2) > 2) onLineStatus = 0;
                }
                if(baseInfo.getOnLineStatus() == null ||onLineStatus != baseInfo.getOnLineStatus()){
                    baseInfo.setOnLineStatus(onLineStatus);
                    updateBaseList.add(baseInfo);
                }
            }
            if(updateBaseList.size()>0){
                deviceObdBaseInfoService.updateList(updateBaseList);
            }
            System.out.println("obd在线状态更新完成");
        }
    }

    /**
     *  每天早上1点计算前一天所有设备的面积
     * @author tm
     * @date 2023-09-08 17:42
     */
    //使用
    @Scheduled(cron = "0 0 1 * * ?")
    public void calObdArea(){
        if(SysConfig.getJobSwitch()==0)return;
        Date date = DateUtils.addDate(new Date(),0,0,-1,0,0,0,0);
        String time = DateUtils.parseDateToStr(date,DateUtils.DATE_FORMAT_YYYYMMDD);
        PythonUtils.call(time,null,null);
    }


//    @Scheduled(cron = "0 50 19 * * ?")
    public void callObd78Area(){
        Date d = DateUtils.parseStrToDate("2023-07-01",DateUtils.DATE_FORMAT_YYYY_MM_DD);
        boolean flag = true;
        while (flag){
            String str = DateUtils.parseDateToStr(d,DateUtils.DATE_FORMAT_YYYYMMDD);
            PythonUtils.call(str,null,null);
            System.out.println(str);
            d = DateUtils.addDate(d,0,0,1,0,0,0,0);
            if(DateUtils.getMonthInt(d) == 9){
                flag = false;
            }
        }
    }

    //临时统计data_obd_gps_info中的信息
//    @Scheduled(cron = "0 21 20 * * ?")
    public void statisObdGpsInfo(){
        List<DataObdGpsInfo> resultList = new ArrayList<>();
        GetDataObdGpsInfoDO getDataObdGpsInfoDO = new GetDataObdGpsInfoDO();
        getDataObdGpsInfoDO.setSortRow("id");
        getDataObdGpsInfoDO.setSortOrder("asc");
        List<DataObdGpsInfo> list = dataObdGpsInfoService.getAllList(getDataObdGpsInfoDO);
        for(DataObdGpsInfo info :list){
            if(info.getId() == 3463)break;
            String zdh = info.getZdh();
            if(zdh.indexOf("5600109")==-1)continue;
            String shortZdh = zdh.substring(zdh.length()-5,zdh.length());
            GetDeviceObdBaseInfoDO getDeviceObdBaseInfoDO = new GetDeviceObdBaseInfoDO();
            getDeviceObdBaseInfoDO.setDtu(shortZdh);
            getDeviceObdBaseInfoDO.setSortRow("id");
            getDeviceObdBaseInfoDO.setSortOrder("asc");
            List<DeviceObdBaseInfo> baseList = deviceObdBaseInfoService.getAllList(getDeviceObdBaseInfoDO);
            if(baseList == null || baseList.size() ==0 )continue;
            DeviceObdBaseInfo baseInfo = null;
            if(baseList.size() == 1){
                baseInfo = baseList.get(0);
            }else{
                DeviceObdBaseInfo bInfo = selectWD(baseList);
                if(bInfo!=null)baseInfo = bInfo;
            }
            if(baseInfo == null) continue;
            SimInfo simInfo = simInfoService.getByImei(baseInfo.getSim());
            if(simInfo!=null){
                info.setDtu(baseInfo.getDtu());
                info.setSim(baseInfo.getSim());
                info.setImei(baseInfo.getImei());
                info.setGys(simInfo.getSupplier());
                resultList.add(info);
            }
            System.out.println("======处理了：" + resultList.size());
        }
        if(resultList.size()>0){
            dataObdGpsInfoService.updateList(resultList);
        }
    }
    private DeviceObdBaseInfo selectWD(List<DeviceObdBaseInfo> baseList){
        int index = -1;
        for(int i =0;i<baseList.size();i++){
            DeviceObdBaseInfo info = baseList.get(i);
            if(info.getFactoryUserId() == null || info.getFactoryUserId() == 0)continue;
            if(info.getFactoryUserId()==733){
                if(index==-1){
                    index = i;
                }else{
                    return null;
                }
            }
        }
        if(index!=-1)return baseList.get(index);
        return null;
    }
    /**
     * 发送定位信息给环保部
     * @author tm
     * @date 2023-12-17 21:57
     */
    @Scheduled(cron = "0 18 10 26 03 ?")
    public void sendGpsToFk(){
        String tableName = "device_obd_gps_info_20230531";
        GetDeviceObdGpsInfoDO getDeviceObdGpsInfoDO = new GetDeviceObdGpsInfoDO();
        getDeviceObdGpsInfoDO.setTableName(tableName);
        getDeviceObdGpsInfoDO.setSortRow("time");
        getDeviceObdGpsInfoDO.setSortOrder("asc");
        getDeviceObdGpsInfoDO.setDtu("02ai990005748");
        getDeviceObdGpsInfoDO.setIsEffective("1");
        List<DeviceObdGpsInfo> gpsList = deviceObdGpsInfoService.getAllList(getDeviceObdGpsInfoDO);
        for(int i=0;i<gpsList.size();i++){
            DeviceObdGpsInfo info = gpsList.get(i);
//            if(info.getId() <6060300) continue;
            SocketTest.sendGps(info.getLon(),info.getLat());
            try{
                Thread.sleep(5000);
            }catch (Exception e){
                e.printStackTrace();
            }
            if(i==200){
                SocketTest.loginInOfMachine();
            }
            if(i == 300){
                SocketTest.loginOutOfMachine();
            }
            if(i==400){
                SocketTest.loginOut();
            }

            if(i==880){
                SocketTest.sendTamperAlarm(info.getLon(),info.getLat());
            }
        }
    }


    /**
     *每天 1点 统计前一天的工况信息
     * @author tm
     * @date 2022-10-28 14:51
     */
    @Scheduled(cron = "0 30 1 * * ?")
    public void workInfoInDay(){
        Date date = DateUtils.addDate(new Date(), 0, 0, -1, 0, 0, 0, 0);
        String str = DateUtils.parseDateToStr(date, DateUtils.DATE_FORMAT_YYYYMMDD);
        List<Map<String,Object>> list = device25ObdInfoService.getObdInfoNumByDay(str);
        System.out.println(str + "===" + list.size());
        if (list != null && list.size() > 0) {
            for (Map<String,Object> map: list) {
                System.out.println("------------------------------");
                String dtu = map.get("dtu").toString();
                System.out.println("&&&&&&&&&&date :" +str);
                int workTime1 = 0;//开始时工时
                Date startTime = new Date();
                GetDevice25ObdInfoDO getDevice25ObdInfoDO = new GetDevice25ObdInfoDO();
                getDevice25ObdInfoDO.setDtu(dtu);
                getDevice25ObdInfoDO.setTableName("device_25_obd_info_"+str);
                getDevice25ObdInfoDO.setSortRow("createTime");
                getDevice25ObdInfoDO.setSortOrder("asc");
                List<Device25ObdInfo> obdList = device25ObdInfoService.getAllList(getDevice25ObdInfoDO);
                boolean isWork = false;
                int workTime2 = 0 ;//结束时工时
                if(obdList!=null&&obdList.size()>0){
                    workTime1 = Integer.valueOf(obdList.get(0).getZcgzsj());
                    startTime = obdList.get(0).getCreateTime();
                    workTime2 = Integer.valueOf(obdList.get(obdList.size()-1).getZcgzsj());
                    for(Device25ObdInfo info:obdList){
                        if(info.getDcdy()!=null  && !"".equals(info.getDcdy()) && Double.valueOf(info.getDcdy()) >10){
                            isWork = true;
                            break;
                        }
                    }
                }

                DeviceObdBaseInfo baseInfo  = deviceObdBaseInfoService.getByDtu(dtu);
                if(baseInfo.getStartupTime() == null && isWork){
                    baseInfo.setStartupTime(startTime);
                }
                baseInfo.setWorkTime(workTime2);
                deviceObdBaseInfoService.update(baseInfo);
                if(workTime1 != workTime2){
                    DeviceObdWorkTimeDayStatisticsInfo info = new DeviceObdWorkTimeDayStatisticsInfo();
                    info.setDtu(dtu);
                    info.setDataDate(date);
                    info.setWorkTime(workTime2-workTime1);
                    deviceObdWorkTimeDayStatisticsInfoService.save(info);
//                    device25ObdInfoService.saveObdWorkTimeByDay(info);
//                    System.out.println("&&&&&&&&&&&&当天作业的设备数：" + num);
                }
                System.out.println("------------------------------");
            }
        }
    }
}
